package io.github.uicdb.badskill.network;

import io.github.uicdb.badskill.SkillOption;
import io.github.uicdb.badskill.SkillOptionManager;
import io.github.uicdb.badskill.SkillPage;
import io.github.uicdb.badskill.SkillPageManager;
import lombok.RequiredArgsConstructor;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.network.NetworkEvent;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;

@RequiredArgsConstructor
public class SkillPageSyncPackage {
    private final Map<ResourceLocation, SkillPage> pageMap;
    public static SkillPageSyncPackage create(){
        return new SkillPageSyncPackage(SkillPageManager.INSTANCE.PAGES);
    }
    public  void toBytes(FriendlyByteBuf buf) {
       buf.writeMap(pageMap, FriendlyByteBuf::writeResourceLocation, (buf1, page) -> page.toNetwork(buf1));
    }

    public static SkillPageSyncPackage create(FriendlyByteBuf buf) {
        Map<ResourceLocation, SkillPage> map=buf.readMap(FriendlyByteBuf::readResourceLocation, SkillPage::fromNetwork);
        return new SkillPageSyncPackage(map);
    }

    public  void handle(Supplier<NetworkEvent.Context> contextSupplier) {
        var context=contextSupplier.get();
        context.enqueueWork(() -> {
            if(context.getDirection().getReceptionSide()== LogicalSide.CLIENT){
                SkillPageManager.INSTANCE.PAGES.clear();
                SkillPageManager.INSTANCE.PAGES.putAll(pageMap);
                SkillPageManager.INSTANCE.getPageList().clear();
                SkillPageManager.INSTANCE.getPageList().addAll(pageMap.values());
            }
        });
        context.setPacketHandled(true);
    }
}
